package com.abefd77.demo.mytflitestartup

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Matrix
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Surface
import android.view.ViewGroup
import android.widget.Toast
import androidx.camera.core.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.abefd77.remoteservice.mytflitestartup.R
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.util.concurrent.Executors

private const val REQUIRED_PERMISSION_CODE_RANGE = 1
private const val IMAGE_REQUIRED_CODE = 2
private val REQUIRED_PERMISSIONS = arrayOf(android.Manifest.permission.CAMERA,android.Manifest.permission.READ_EXTERNAL_STORAGE);



class MainActivity : AppCompatActivity() {


    private var imageCapture : ImageCapture? = null
    private var executor = Executors.newSingleThreadExecutor()
    private var lensFacing = CameraX.LensFacing.BACK

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化按钮事件
        initBtnEvent()

        // 检查权限
        if(allPermissionGranted()) {
            camera_view.post { initCamera() }
        }else{
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUIRED_PERMISSION_CODE_RANGE)
        }

    }
    /**
     * 初始化按钮事件
     */
    private fun initBtnEvent(){
        //发生旋转后取景器重新计算布局
        camera_view.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            updateTransform()
        }

        cam_cap_btn.setOnClickListener {
            val file = File(externalMediaDirs.first(), "${System.currentTimeMillis()}.jpg")
            imageCapture?.takePicture(file, executor,
            object : ImageCapture.OnImageSavedListener{
//                TODO：检查为何在AVD中存储成功后却调用OnError原因
                override fun onError(imageCaptureError: ImageCapture.ImageCaptureError,
                                     message: String,
                                     cause: Throwable?) {
                    val msg = "保存失败：$message"
                    camera_view.post {
                        Toast.makeText(baseContext, msg, Toast.LENGTH_LONG).show()
                    }
                }

                override fun onImageSaved(file: File) {
                    val msg = "保存成功，文件以保存至 ${file.absolutePath}"
                    camera_view.post {
                        Toast.makeText(baseContext, msg, Toast.LENGTH_LONG).show()
                    }
                    //跳转到预览窗体
                    toPreview(Uri.fromFile(File(file.absolutePath)))
                }
            })
        }

        cam_flip_btn.setOnClickListener {
            lensFacing = if(CameraX.LensFacing.FRONT == lensFacing){
                CameraX.LensFacing.BACK
            }else{
                CameraX.LensFacing.FRONT
            }
            initCamera()
        }

        pic_load_btn.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            startActivityForResult(intent, IMAGE_REQUIRED_CODE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            IMAGE_REQUIRED_CODE -> {
               val imgUri : Uri ? = data?.data //获取系统返回照片的URI
//                val intent = Intent(this, PreviewActivity::class.java)
//                intent.putExtra()
                if (imgUri != null) {
                    toPreview(imgUri)
                }

            }
        }
    }

    private fun toPreview(uri: Uri){
        val intent = Intent(this@MainActivity, PreviewActivity::class.java)
        intent.putExtra("path", uri.toString())
        startActivity(intent)
    }

    /**
     * 检查权限
     */
    private fun allPermissionGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
    }


    /**
     * 初始化摄像头
     */
    private fun initCamera(){
        // 释放摄像头生命周期
        CameraX.unbindAll();
//        配置相机预览
        val previewConfig = PreviewConfig.Builder()
            .apply {
                // 摄像头比例
                setTargetAspectRatio(AspectRatio.RATIO_16_9);
                // 默认
                setLensFacing(lensFacing);
            }.build();
        // 创建预览
        val preview = Preview(previewConfig)
        // 每次更新取景器后重新计算布局
        preview.setOnPreviewOutputUpdateListener {
            val present = camera_view.parent as ViewGroup
            present.removeView(camera_view)
            present.addView(camera_view,0)
            // api30 camera_view.surfaceTexture is val and can not assign
            camera_view.surfaceTexture = it.surfaceTexture
            updateTransform()
        }
        val imageCaptureConfig = ImageCaptureConfig.Builder()
            .apply {
                // 设置拍摄模式
                //  MIN_LATENCY 优先保证速度，可能降低质量
                //  MAX_QUALITY 优先保障质量，可能降低速度
                setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
                setTargetAspectRatio(AspectRatio.RATIO_16_9)
                setLensFacing(lensFacing)
            }.build()
        // 捕捉图像实例
        imageCapture = ImageCapture(imageCaptureConfig)
        CameraX.bindToLifecycle(this, preview, imageCapture)
    }


    /**
     * 根据设备方向的变化，更新视图
     */
    private fun updateTransform() {
        val matrix = Matrix()
        // 计算取景器的中心
        val centerX = camera_view.width / 2f
        val centerY = camera_view.height / 2f
        //校正预览输出以考虑显示旋转
        val rotationDegrees = when (camera_view.display.rotation) {
            Surface.ROTATION_0 -> 0
            Surface.ROTATION_90 -> 90
            Surface.ROTATION_180 -> 180
            Surface.ROTATION_270 -> 270
            else -> return
        }
        matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY)
        //添加到TextureView
        camera_view.setTransform(matrix)
    }
}